from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from typing import List, Optional
from db import get_db
from api.routes.auth import get_current_user
from models.user import User
from models.medical_terms import MedicalTerm
from schemas.terminology import MedicalTermCreate, MedicalTermUpdate, MedicalTermOut

router = APIRouter()

@router.get("/", response_model=List[MedicalTermOut])
def list_medical_terms(
    search_term: Optional[str] = Query(None, description="搜索术语"),
    db: Session = Depends(get_db)
):
    """
    获取术语列表
    """
    try:
        query = db.query(MedicalTerm)

        if search_term:
            query = query.filter(
                MedicalTerm.term_chinese.contains(search_term) |
                MedicalTerm.term_lisu.contains(search_term) |
                MedicalTerm.term_vietnamese.contains(search_term)
            )

        items = query.order_by(MedicalTerm.id.desc()).all()
        return items

    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取术语列表失败: {str(e)}"
        )

@router.get("/{term_id}", response_model=MedicalTermOut)
def get_medical_term(
    term_id: int,
    db: Session = Depends(get_db)
):
    """
    获取特定术语详情
    """
    try:
        term = db.query(MedicalTerm).filter(MedicalTerm.id == term_id).first()
        if not term:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="术语不存在"
            )
        return term

    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取术语详情失败: {str(e)}"
        )

@router.post("/", response_model=MedicalTermOut)
def create_medical_term(
    data: MedicalTermCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    创建新术语（需要管理员权限）
    """
    try:
        # 检查是否已存在相同术语
        existing_term = db.query(MedicalTerm).filter(
            MedicalTerm.term_chinese == data.term_chinese
        ).first()

        if existing_term:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="术语已存在"
            )

        term = MedicalTerm(
            term_chinese=data.term_chinese,
            term_lisu=data.term_lisu,
            term_vietnamese=data.term_vietnamese,
            term_laowu=data.term_laowu,
            term_miandian=data.term_miandian
        )
        db.add(term)
        db.commit()
        db.refresh(term)
        return term

    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"创建术语失败: {str(e)}"
        )

@router.put("/{term_id}", response_model=MedicalTermOut)
def update_medical_term(
    term_id: int,
    data: MedicalTermUpdate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    更新术语（需要管理员权限）
    """
    try:
        term = db.query(MedicalTerm).filter(MedicalTerm.id == term_id).first()
        if not term:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="术语不存在"
            )

        # 更新术语信息
        for field, value in data.dict(exclude_unset=True).items():
            setattr(term, field, value)

        db.commit()
        db.refresh(term)
        return term

    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"更新术语失败: {str(e)}"
        )

@router.delete("/{term_id}")
def delete_medical_term(
    term_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    删除术语（需要管理员权限）
    """
    try:
        term = db.query(MedicalTerm).filter(MedicalTerm.id == term_id).first()
        if not term:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="术语不存在"
            )

        db.delete(term)
        db.commit()
        return {"message": "术语删除成功"}

    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"删除术语失败: {str(e)}"
        )